#include "CChar.h"
#include "CSemaphore.h"
#include "CGuildShopHandler.h"
#include "CGuildShop.h"
#include "CGuildSellMenuPacket.h"

CGuildSellMenuPacket::CGuildSellMenuPacket(unsigned short guildID, CChar * schar) {
	unsigned char packetCount = 0;
	unsigned char itemCount = 0;
	createPacket();
	CGuildShop * guildShop = NULL;
	CGuildShopHandler::waitGuildShopList();
	guildShop = CGuildShopHandler::getGuildShop(guildID);
	if (guildShop != NULL) {
		for(unsigned char slotID = 1; slotID <= guildShop->getSize(); slotID++) {
			CItem * item = NULL;
			item = guildShop->getItem(slotID);
			if(item != NULL) {
				unsigned short itemID = item->getId();
				unsigned char quantity = (unsigned char)item->getQuantity();
				unsigned char max = item->getStackSize();
				unsigned long price = guildShop->getSellPrice(itemID);

				memcpy(data+(0x08 * itemCount)+0x04-0x04, &itemID, 2);
				data[(0x08 * itemCount)+0x06-0x04] = quantity;
				data[(0x08 * itemCount)+0x07-0x04] = max;
				memcpy(data+(0x08 * itemCount)+0x08-0x04, &price, 4);

				itemCount++;
				data[0xF4-0x04] = itemCount;
			}
			// Max 30 items per packet
			if(itemCount == 30) {
				// 0x40 = first packet
				if(packetCount == 0)
					data[0xF5-0x04] = 0x40;
				else
					data[0xF5-0x04] = packetCount;
				
				// Send the packet
				schar->quePacket(*this);

				// Reset the packet
				itemCount = 0;
				createPacket();

				packetCount++;
			}
		}
	}
	if(itemCount > 0) {
		data[0xF4-0x04] = itemCount;

		// 0x80 = last packet
		data[0xF5-0x04] += (0x80 + packetCount);
	}
	CGuildShopHandler::exitGuildShopList();
}

CGuildSellMenuPacket::~CGuildSellMenuPacket() {
}

void CGuildSellMenuPacket::createPacket() {
	this->type		=	0x85;
	this->size		=	0x7C;

	memset(this->data, 0, sizeof(data));
}
